package com.open.party.cloud.view.comm

import android.graphics.Typeface
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import cn.android.x.model.AppVersionEntity
import cn.android.x.model.data.ResultInfo
import com.gyf.immersionbar.ImmersionBar
import com.jiangyy.easydialog.CommonDialog
import com.king.app.dialog.AppDialog
import com.king.app.dialog.AppDialogConfig
import com.king.app.updater.AppUpdater
import com.open.party.cloud.R
import com.open.party.cloud.model.UserEntity
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.view.login.LoginActivity
import com.open.party.cloud.view.mine.MineMainActivity
import com.open.party.cloud.viewModel.BaseViewModel
import com.sinothk.android.utils.XUtils
import com.tencent.bugly.crashreport.CrashReport
import kotlinx.android.synthetic.main.title_view_for_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open abstract class MainBaseActivity : AppCompatActivity() {
    override fun onResume() {
        super.onResume()
        EventBus.getDefault().register(this)
    }

    override fun onPause() {
        super.onPause()
        EventBus.getDefault().unregister(this)
    }

    private var baseViewModel: BaseViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        ImmersionBar.with(this).statusBarDarkFont(false).init()
        XUtils.page().addActivity(this)
        baseViewModel = BaseViewModel()
        initTab()
        initNetData()

        val fontFace = Typeface.createFromAsset(this.assets, "fonts/FZXBSJW.TTF")
        mineInfoBtn.typeface = fontFace
        mineInfoBtn.setOnClickListener {
            XUtils.intent().openActivity(this@MainBaseActivity, MineMainActivity::class.java).start()
        }
    }

    private fun initNetData() {
        if (!XUtils.net().isConnected) {
            return
        }

        checkNewVersion()

        Thread(Runnable { // 更新token
            if (LocalCache.getAutoLogin()) {
                val account = LocalCache.getLoginAccount()
                val pwd = LocalCache.getPwd()
                baseViewModel!!.updateToken(account, pwd)
            }
        }).start()
    }

    abstract fun initTab()

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(false)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun checkNewVersion() {
        baseViewModel!!.getAppInfoForLastVersion("getAppInfoForLastVersionAtMain")
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun receiveEventBus(resultInfo: ResultInfo<AppVersionEntity>) {

        if ("getAppInfoForLastVersionAtMain" != resultInfo.eventType) {
            return
        }

        when (resultInfo.code) {
            ResultInfo.SUCCESS -> {
                if (resultInfo.data == null) {
                    return
                }

                val appVersion = resultInfo.data

                if (resultInfo.data.verNumber > XUtils.app().appVersionCode) {
                    //简单弹框升级
                    val config = AppDialogConfig()
                    config.setTitle("新版本升级")
                        .setOk("升级")
                        .setContent(XUtils.string().getNotNullValue(appVersion.updateContent)).onClickOk = View.OnClickListener {
                        if (XUtils.string().isNotEmpty(appVersion.filePath)) {
                            AppUpdater.Builder()
                                .serUrl(appVersion.filePath)
                                .build(this)
                                .start()
                        } else {
                            XUtils.toast().show("地址不可用")
                        }
                        AppDialog.INSTANCE.dismissDialog()
                    }
                    AppDialog.INSTANCE.showDialog(this@MainBaseActivity, config)
                }
                LocalCache.setAppVersion(appVersion)
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
            }
        }
//
//
//        if (resultInfo.code == ResultInfo.SUCCESS) {
//            val appVersion: AppVersionEntity = resultInfo.getData()
//            if (appVersion != null) {
//
//            }
//        } else if (resultInfo.code == ResultInfo.TOKEN_OVERDUE) {
//        } else {
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun receiveStudentEventBus(result: ResultInfo<UserEntity>) {

        if (result.eventType != "updateToken") {
            return
        }

        when (result.code) {
            ResultInfo.SUCCESS -> { //
                LocalCache.setLoginUser(result.data)
                LocalCache.setAutoLogin(true)
            }
            else -> {
                LocalCache.logout()

                CommonDialog.Builder(this)
                    .setTitle("登录过期")
                    .setMessage("登录过期，请重新登录？")
                    .setPositiveButton("重新登录") {
                        XUtils.intent().openActivity(this@MainBaseActivity, LoginActivity::class.java)
                            .start()
                    }.setNegativeButton("取消") {
                    }.show()
            }
        }
    }
}